package com.bcxj.serviceuser.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bcxj.internalcommon.constant.CommonConstant;
import com.bcxj.internalcommon.constant.CommonStatusEnum;
import com.bcxj.internalcommon.dto.VerificationCodeDTO;
import com.bcxj.internalcommon.entity.TravelUser;
import com.bcxj.internalcommon.response.ResponseResult;
import com.bcxj.internalcommon.vo.TravelUserVO;
import com.bcxj.serviceuser.mapper.TravelUserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiaoleilu.hutool.util.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * ClassName: TravelUserService
 * Package: com.bcxj.serviceuser.service
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/2/12 21:59
 * @Version 1.0
 * @Since 1.0
 */
@Service
public class UserService {

    @Autowired
    private TravelUserMapper travelUserMapper;

    public ResponseResult loginOrRegister(VerificationCodeDTO verificationCodeDTO) {
        String phone = verificationCodeDTO.getUserPhone();
        // 1 检查用户是否存在
        Long count = travelUserMapper.selectCount(new LambdaQueryWrapper<TravelUser>().eq(TravelUser::getUserPhone, phone));

        // 1.2 用户已存在
        if (count > 0) {
            return ResponseResult.success("用户已存在");
        }

        // 2. 增加用户
        // 用户不存在则插入数据
        TravelUser user = new TravelUser();


        // 这里需要注意一个点，就是这里的主键没有设置，但由于使用的是mybatis-plus 所以主键会自动生成
        user.setUserPhone(phone);
        user.setUserName("user-" + generateRandomString(10));
        user.setUserGender((byte) 0);
        user.setState((byte) 0);

        LocalDateTime now = LocalDateTime.now();
        user.setGmtCreate(now);
        user.setGmtModified(now);

        travelUserMapper.insert(user);

        return ResponseResult.success("新用户注册成功");

    }


    private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    private static String generateRandomString(int length) {
        Random random = new Random();
        StringBuilder builder = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            builder.append(ALPHA_NUMERIC_STRING.charAt(random.nextInt(ALPHA_NUMERIC_STRING.length())));
        }
        return builder.toString();
    }


    /**
     * 更新用户的信息
     * @param travelUser
     * @return
     */
    public ResponseResult updateUser(TravelUser travelUser) {
        // 查询用户是否存在
        TravelUser user = travelUserMapper.selectOne(new LambdaQueryWrapper<TravelUser>()
                .eq(TravelUser::getId, travelUser.getId())
                .eq(TravelUser::getState, 0));
        if(user == null) {
            return ResponseResult.fail(CommonStatusEnum.USER_NOT_FUND);
        }
        // 更新数据
        travelUserMapper.updateById(travelUser);
        return ResponseResult.success();
    }


    /**
     * 根据用户的手机号查询用户的信息
     * @param userPhone
     * @return
     */
    public ResponseResult<TravelUserVO> getUserVOByUserphone(String userPhone) {
        LambdaQueryWrapper<TravelUser> travelUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        travelUserLambdaQueryWrapper.eq(TravelUser::getUserPhone, userPhone);
        TravelUser travelUser = travelUserMapper.selectOne(travelUserLambdaQueryWrapper);
        TravelUserVO travelUserVO = new TravelUserVO();
        if(travelUser == null) {
            return ResponseResult.fail(CommonStatusEnum.USER_NOT_FUND);
        }
        BeanUtil.copyProperties(travelUser, travelUserVO);
        return ResponseResult.success(travelUserVO);
    }


    /**
     * 分页查询数据
     * @param pageNo
     * @return
     */
    public ResponseResult list(Integer pageNo) {
        // 1.设置当前页码和每页显示的记录条数
        PageHelper.startPage(pageNo, CommonConstant.PAGE_SIZE);
        // 2.获取数据（PageHelper会自动给SQL语句添加limit）
        List<TravelUser> users = travelUserMapper.selectList(null);

        // 3.2 处理数据
        ArrayList<TravelUserVO> travelUserVOS = new ArrayList<>();
        for (int i = 0; i < users.size(); i++) {
            TravelUserVO travelUserVO = new TravelUserVO();
            BeanUtil.copyProperties(users.get(i), travelUserVO);
            travelUserVOS.add(travelUserVO);
        }
        // 3.将分页数据封装到PageInfo
        // PageInfo<TravelUserVO> vipPageInfo = new PageInfo<>(travelUserVOS);
        PageInfo<TravelUser> userPageInfo = new PageInfo<>(users);
        return ResponseResult.success(userPageInfo);
    }

    /**
     * 禁用用户
     * @param id
     * @return
     */
    public ResponseResult setState(Long id, Integer state) {
        TravelUser travelUser = travelUserMapper.selectById(id);
        if(null == travelUser) {
            return ResponseResult.fail("系统无该用户");
        }
        travelUser.setState(state.byteValue());
        travelUserMapper.updateById(travelUser);
        return ResponseResult.success();
    }
}
